/*
*
**/

import 'package:flutter/material.dart';

import 'tabbarview_page1.dart';
import 'tabbarview_page2.dart';
import 'tabbarview_page3.dart';

class AutomaticKeepAliveIndex extends StatefulWidget {
  const AutomaticKeepAliveIndex({Key? key}) : super(key: key);

  @override
  _AutomaticKeepAliveIndexState createState() => _AutomaticKeepAliveIndexState();
}

class _AutomaticKeepAliveIndexState extends State<AutomaticKeepAliveIndex> with SingleTickerProviderStateMixin {
  int activeIndex = 1;

  final tabBarViewK1 = GlobalKey();
  final tabBarViewK2 = GlobalKey();
  final tabBarViewK3 = GlobalKey();

  late final List<GlobalKey> tabKs = [tabBarViewK1, tabBarViewK2, tabBarViewK3];

  static const List<Tab> _tabs = [
    Tab(icon: Icon(Icons.directions_car_rounded)),
    Tab(icon: Icon(Icons.directions_transit)),
    Tab(icon: Icon(Icons.directions_bike)),
  ];

  late final TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: _tabs.length, vsync: this)
      ..addListener(() {
        final activeIndex = _tabController.index;
        print("activeIndex:$activeIndex");
        final State? state = tabKs[activeIndex].currentState;
        if (state != null) {
          if (activeIndex == 0) {
            (state as Page1State).updateData();
          } else if (activeIndex == 1) {
            (state as Page2State).updateData();
          } else if (activeIndex == 2) {
            (state as Page3State).updateData();
          }
        }
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('tabbarview'),
        bottom: TabBar(
          controller: _tabController,
          onTap: (index) {},
          tabs: _tabs,
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          Page1(
            key: tabBarViewK1,
          ),
          Page2(
            key: tabBarViewK2,
          ),
          Page3(
            key: tabBarViewK3,
          ),
        ],
        physics: const BouncingScrollPhysics(),
      ),
    );
  }
}
